<?php

namespace Xin\Hint\Laravel;

use Illuminate\Http\Exceptions\HttpResponseException;
use Xin\Hint\Contracts\Render;
use Xin\Hint\HintHandler;

abstract class AbstractRender implements Render
{

	/**
	 * @var HintHandler
	 */
	protected $hintHandler;

	/**
	 * 设置提示器服务
	 * @param HintHandler $hintHandler
	 * @return void
	 */
	public function setHintHandler(HintHandler $hintHandler)
	{
		$this->hintHandler = $hintHandler;
	}

	/**
	 * @inheritDoc
	 */
	public function output($response, callable $callback = null)
	{
		if (is_callable($callback)) {
			call_user_func($callback, $response);
		}

		throw new HttpResponseException($response);
	}

	/**
	 * 优化数据
	 * @param mixed $data
	 * @return mixed
	 */
	public function optimizeData($data)
	{
		if (is_object($data)) {
			$data->time = now()->getTimestamp();
		} else {
			$data['time'] = now()->getTimestamp();
		}

		return $data;
	}

	/**
	 * @param string $url
	 * @return string
	 */
	public function parseUrl($url)
	{
		return (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)url($url ?: '');
	}

	/**
	 * 根据业务数据判断是否是成功行为
	 * @param mixed $data
	 * @return bool
	 */
	protected function isSuccess($data)
	{
		if (is_object($data)) {
			$code = $data->code;
		} else {
			$code = $data['code'];
		}

		return $code === 1;
	}

}
